package com.shiguiwu.springmybatis.mybatis;

import cn.hutool.core.io.LineHandler;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @description: 数据库操作
 * @author: stone
 * @date: Created by 2021/6/21 19:20
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.mybatis
 */
public class BookUtils {

    public static SqlSessionFactory FACTORY = null;

    static {
        try {
            FACTORY = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    @FunctionalInterface
    public interface SessionCall<O> {
        O call(SqlSession sqlSession);
    }


    @FunctionalInterface
    public interface MapperCall<T,O> {
        O call(T mapper) ;
    }



    public static <O> O call(SessionCall<O> sessionCall) {
        try (SqlSession sqlSession = FACTORY.openSession(true);) {
            return sessionCall.call(sqlSession);
        }
    }

    public static <T, O> O callMapper(Class<T> clzz, MapperCall<T, O> mapper)throws Exception {
        SessionCall<O> c = session -> mapper.call(session.getMapper(clzz));
        return call(c);
    }







}
